// src/routes/login/+page.server.ts
import { fail, redirect } from '@sveltejs/kit';
import type { Actions } from './$types';
import { Md5 } from 'ts-md5';
import { reqLogin } from '$lib/api/server/sys/user/index';
import { z } from 'zod';

/* 1. 定义并校验表单结构 */
const loginSchema = z.object({
	account: z.string().trim().min(1, '账号不能为空'),
	password: z.string().trim().min(1, '密码不能为空')
});

export const actions: Actions = {
	default: async (event) => {
		const { request, cookies } = event; 
		const formData = Object.fromEntries(await request.formData());
		const parseResult = loginSchema.safeParse(formData);		
		if (!parseResult.success) {
			// 把第一条错误抛给前端
			return fail(400, { failure: { message: parseResult.error.issues[0].message } });
		}
		const { account, password } = parseResult.data;		
		try {
			/* 1. 调后端接口或查库验证 */
			const token = (await reqLogin(event,{
				account: account,
				password: Md5.hashStr(password)
			})) as unknown as string;			
			// 未获取到token
			if (!token) return fail(400, { wrong: true });			

			/* 2. 写 HttpOnly Cookie（单位：秒） */
			const maxAge = 7 * 24 * 60 * 60; // 7 天
			cookies.set('dhzy_token', token, {
				path: '/',
				httpOnly: true,
				sameSite: 'lax',
				secure: false, // 本地 false
				maxAge
			});									
		} catch (error) {
			console.error('登录失败:', error);
			return fail(500, {
				failure: { message: '服务器错误，登录失败' }
			});
		};
		/* 3. 跳后台 ：redirect就是 throw，不被 catch 吃掉，就把redirect写在try外面*/  		
		redirect(302, '/home');
	}
};
